package com.sunlands.zlcx.usercenter.util;

import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.StdoutLogger;
import com.sunlands.zlcx.usercenter.config.P6SpyConfig;
import com.sunlands.zlcx.usercenter.exception.SendExceptionUtil;
import com.sunlands.zlcx.usercenter.exception.SqlTimeOutException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

@Slf4j
@Data
public class P6SpyLogger extends StdoutLogger {
    public static Boolean print;
    public static List<String> containSql;


    /**
     * 重写输出方法
     *
     * @param connectionId 连接id
     * @param now          当前时间
     * @param elapsed      执行时长，包括执行 SQL 和处理结果集的时间(可以参考来调优)
     * @param category     语句分类，statement、resultset 等
     * @param prepared     查询语句。可能是 prepared statement，表现为 select * from table1 where c1=?，问号参数形式
     * @param sql          含参数值的查询语句，如 select * from from table1 where c1=7
     */
    @Override
    public void logSQL(int connectionId, String now, long elapsed, Category category, String prepared, String sql) {
        if(Objects.nonNull(print) && elapsed > P6SpyConfig.timeout){
            SendExceptionUtil sendExceptionUtil = SpringContextHolder.getBean(SendExceptionUtil.class);
            String badSql = this.strategy.formatMessage(connectionId, now, elapsed, category.toString(), "-prepared-", sql);
            sendExceptionUtil.sendException("SQL耗时超时：" + elapsed + "毫秒 \n" + badSql, new SqlTimeOutException());
        }
        if(Objects.isNull(print) || print){
            if(Objects.isNull(containSql) || containSql.stream().anyMatch(prepared::startsWith)){
                this.logText(this.strategy.formatMessage(connectionId, now, elapsed, category.toString(), "-prepared-", sql));
            }
        }
    }

    @Override
    public void logText(String text) {
        log.info(text);
    }
}
